package com.originskyseed.platform.api.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.api.i18n.ApiResponseMsg;
import com.originskyseed.platform.api.vo.request.GetAccessTokenRequestVO;
import com.originskyseed.platform.cms.model.CmsProductInfo;
import com.originskyseed.platform.cms.service.ICmsProductInfoService;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.tenant.util.TenantAuthUtil;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.log.model.InterfaceSynchroLog;
import com.originskyseed.platform.log.service.IInterfaceSynchroLogService;
import com.originskyseed.platform.user.service.IUserInfoService;

@Controller
@RequestMapping("/productInfoDataInsert")
@BaseLocaleResource(localeFileName = "i18n_api")
public class ProductInfoDataInsertController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ProductInfoDataInsertController.class);

	@DubboReference
	private ICmsProductInfoService cmsProductInfoService;

	@DubboReference
	private IInterfaceSynchroLogService iInterfaceSynchroLogService;

	@DubboReference
	private IUserInfoService userInfoService;

	/**
	 * 新增产品信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/productInfoInsert.json")
	@RequiredParams(names = { "appkey", "appSecret", "productInfoList" })
	public BaseResponseBody anchorViolationInsert(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 验证授权键值和授权代码
		BaseResponseBody result = this.verificationKeySecret();
		if (result != null)
			return result;

		// 记录日志
		InterfaceSynchroLog interfaceSynchroLog = new InterfaceSynchroLog();
		interfaceSynchroLog.setStartTime(new Date());
		interfaceSynchroLog.setDesc("同步产品信息");
		interfaceSynchroLog.setName("anchorViolationInsert.json");
		interfaceSynchroLog.setType(1);
		try {
			// 接收参数
			List<CmsProductInfo> list = this.getParameterList("productInfoList", CmsProductInfo.class);

			// 新增集合
			List<CmsProductInfo> insertList = new ArrayList<>();
			if (list != null && list.size() > 0) {
				// 查询有没有重复的第三方主键 有则去重
				List<String> otherIdList = list.stream().map(CmsProductInfo::getOtherId).collect(Collectors.toList());
				otherIdList = this.selectRepeatOtherId("OSI_PRODUCT_INFO", otherIdList);

				for (CmsProductInfo productInfo : list) {
					boolean isInsert = selectIsRepeat(productInfo.getOtherId(), otherIdList);
					if (isInsert) {
						productInfo.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
						productInfo.setCreateTime(new Date());
						insertList.add(productInfo);
					}
				}

				// 一次性插入的数量
				int size = 500;
				// 总长度
				int length = insertList.size();
				// 计算可以分成多少组
				int num = (length + size - 1) / size;
				for (int i = 0; i < num; i++) {
					// 开始位置
					int fromIndex = i * size;
					// 结束位置
					int toIndex = (i + 1) * size < length ? (i + 1) * size : length;
					List<CmsProductInfo> newProductInfoList = insertList.subList(fromIndex, toIndex);
					cmsProductInfoService.insertBatch(newProductInfoList);
				}
			}
			interfaceSynchroLog.setState(1);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), ApiResponseMsg.SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), ApiResponseMsg.SAVE_ERROR.getMsg()), e.getMessage(), null);

			interfaceSynchroLog.setState(2);
			interfaceSynchroLog.setErrorLog(e.getMessage());
		}
		interfaceSynchroLog.setEndTime(new Date());
		this.iInterfaceSynchroLogService.insertSelective(interfaceSynchroLog);
		return result;

	}

	/**
	 * 查询有没有重复的第三方主键
	 * 
	 * @param tableName
	 * @param otherIdList
	 * @return
	 * @throws Exception
	 */
	private List<String> selectRepeatOtherId(String tableName, List<String> otherIdList) throws Exception {
		Map<String, Object> map = new HashMap<>();
		map.put("tableName", tableName);
		map.put("list", otherIdList);
		return this.userInfoService.selectRepeatOtherId(map);
	}

	/**
	 * 判断是否重复
	 * 
	 * @param otherId
	 * @param otherIdList
	 * @return
	 * @throws Exception
	 */
	private boolean selectIsRepeat(String otherId, List<String> otherIdList) throws Exception {
		boolean isInsert = true;
		for (String id : otherIdList) {
			if (otherId.equals(id)) {
				isInsert = false;
				break;
			}
		}
		return isInsert;
	}

	/**
	 * 验证授权键值和授权代码
	 * 
	 * @param request
	 * @return
	 */
	private BaseResponseBody verificationKeySecret() {
		// 请求对象
		GetAccessTokenRequestVO requestVO = this.getParameterBean(GetAccessTokenRequestVO.class);
		// 获取第三方授权返回码
		int responseCode = TenantAuthUtil.getInstance().getAuthenticatedResponseCode(requestVO.getAppkey(), requestVO.getAppSecret());
		if (responseCode == 2004) {
			return null;
		} else {
			return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), ApiResponseMsg.APP_KEY_APP_SECRET_ERROR.getMsg()), false);
		}
	}
}
